const express = require('express');
const router = express.Router();

router.get('/allGuest', async (req,res,next) => {
	try{
		const allGuest = await Guest.find({enabled:true}).select(['name','imgUrl','desc','updateTime']).sort({updateTime:-1});
		res.reply(null,allGuest);
	}catch(err){
		res.reply(err);
	}
});

router.get('/guestDetail', async (req,res,next) => {
	try{
		const guestId = req.query.guestId;
		const guest = await Guest.findById(guestId);
		if(!guest) throw {code:404, error:'Guest not found.'};
		// const guestDetail = await guest.findDetail(guest);
		res.reply(null,guest);
	}catch(err){
		res.reply(err);
	}
});

router.post('/', async (req,res,next) => {
	try{
		const {body} = req;
		const {name,imgUrl,desc} = body;
		const guest = Guest.findOne({name:name});
		if(guest) throw {code:101, error:'Guest name exists.Please change another name.'}
		const ret = await Guest.add(body);
		res.reply(null,ret);
	}catch(err){
		res.reply(err);
	}
});

router.post('/:guestId', async (req, res, next) => {
	const guestId = req.params.guestId;
	const {body} = req;
	try{
		const guest = await Guest.findById(guestId);
		if(!guest) throw {code:404, error:'Guest not found.'};
		const ret = await guest.update(body,guest);
		res.reply(null,ret);
	}catch(err){
		res.reply(err);
	}
})

module.exports = router;